package com.qyer.commons.mc.reloader;

import static com.qyer.commons.utils.DBUtils.tryConnect;
import static org.apache.commons.dbutils.DbUtils.closeQuietly;

import com.qyer.commons.mc.converter.Converter;
import com.qyer.commons.persistence.DBResourceManager;
import org.apache.commons.lang3.ArrayUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Collection;

/**
 * User: Z J Wu Date: 2015/09/25 Time: 17:40 Package: com.qyer.dsp.cache.reloader
 */
public class MysqlReloader<T> extends Reloader<T> {

  private Object[] parameters;
  private Converter<Collection<Object[]>, T> converter;

  private DBResourceManager dbResourceManager;

  public MysqlReloader(String sqlStatement, Converter<Collection<Object[]>, T> converter,
                       DBResourceManager dbResourceManager) {
    super(sqlStatement);
    this.converter = converter;
    this.dbResourceManager = dbResourceManager;
  }

  public MysqlReloader(String sqlStatement, Object[] parameters,
                       Converter<Collection<Object[]>, T> converter,
                       DBResourceManager dbResourceManager) {
    super(sqlStatement);
    this.parameters = parameters;
    this.converter = converter;
    this.dbResourceManager = dbResourceManager;
  }

  @Override public T _reload() throws Exception {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Collection<Object[]> results = new ArrayList<>();
    Object[] objects;
    try {
      conn = tryConnect(dbResourceManager.getDataSource(), 10, "MysqlReloader");
      pstmt = conn.prepareStatement(getReloadResource());
      if (ArrayUtils.isNotEmpty(parameters)) {
        for (int i = 0; i < parameters.length; i++) {
          pstmt.setObject(i + 1, parameters[i]);
        }
      }
      rs = pstmt.executeQuery();
      ResultSetMetaData rsmd = rs.getMetaData();
      int i = rsmd.getColumnCount();
      while (rs.next()) {
        objects = new Object[i];
        for (int j = 0; j < i; j++) {
          objects[j] = rs.getObject(j + 1);
        }
        results.add(objects);
      }
    } finally {
      closeQuietly(conn, pstmt, rs);
    }
    return converter == null ? null : converter.convert(results);
  }

}
